//
//  MyInsureViewController.m
//  Inforcollection
//
//  Created by macbook on 15/12/1.
//  Copyright © 2015年 oceansoft.liw. All rights reserved.
//

#import "SendManagementVC.h"
#import "TitleTabView.h"
#import "registerVCcell.h"
#import "BarCodeViewController.h"
#import "PackageAPI.h"
#import "Config.h"
#import "UIView+Ext.h"
#import "Reachability.h"
#import <BaiduMapAPI_Base/BMKMapManager.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "AFNetworking.h"
#import "NotUpdataTool.h"
#define MScrollTag 1000
#define TexfiledTag  415
#define btnPicKTag   234
#define MScrollView_W  _insuranceScrollView.bounds.size.width
#define MScrollView_H  _insuranceScrollView.bounds.size.height

@interface SendManagementVC ()<UITableViewDataSource,UITableViewDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,NSXMLParserDelegate,UIActionSheetDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UIAlertViewDelegate>
{
     NSArray*Rgieterrray;
     NSArray*DataRgister;
     UIImagePickerController *_pickerController;
     UIImageView*IDcardImageV;
     UIActionSheet*progressSheet;
     UIProgressView*progressBar;
     UIButton*cancelButton;
     NSString*_dataStr;
     BMKLocationService *locService;
     UIActivityIndicatorView*activityView;
     NSString *addressStr;
     NSString *reportAddress;
     UIImage*AddImage;
     UIImage*FistitemImage;
     UIImage*SecondItemImage;
     UIImage*FistOtherImage;
     UIImage*SecondOtherImage;
     UIImage*ItemImage;
     UIPickerView*PickView;
     UIView*backView;
     NSMutableArray*NotUpDataArray;
     UIView*contextbtnV;
     UITextField*IDCardFiled;
    BOOL IsbringIDCar;
    BOOL NameIsEnd;
    NSMutableArray*NotUpImageArray;
    long  ImageCount;
 
}
@property (nonatomic)BOOL  isProgressCanceled;
@property (strong, nonatomic) IBOutlet UIImageView *blackImage;
@property(strong,nonatomic) UITableView*Registertable;
@property(strong,nonatomic)NSMutableArray*Photos1Array;
@property(strong,nonatomic)NSMutableArray*Photos2Array;
@property (nonatomic, copy) NSString *resultStr;
@property(strong,nonatomic)NSDictionary*pickerDic;
@property(strong,nonatomic)NSArray*provinceArray;
@property(strong,nonatomic)NSArray*selectedArray;
@property(strong,nonatomic)NSArray*cityArray;
@property(strong,nonatomic)NSArray*townArray;
@end
@implementation SendManagementVC

@synthesize Registertable;

-(void)viewDidLoad
{
    [super viewDidLoad];
    
   
    
    NotUpDataArray=[NSMutableArray array];
    NotUpImageArray=[NSMutableArray array];
    IDcardImageV=[[UIImageView alloc]init];
    locService=[[BMKLocationService alloc]init];
    locService.delegate=self;
    [locService startUserLocationService];
    [self setNaviBarTitle:@"寄件管理"];
    [self setNavBarColor:APPNavibackColor];
    IsbringIDCar=NO;
    NameIsEnd=NO;
    ImageCount=0;
    DataRgister=@[@"*单号信息:",@" 寄件信息",@"*身份证号:",@"*姓        名：",@"*手机号码:",@"*寄件地址:",@" 收件信息",@"*手机号码:",@"*姓        名:",@"*收件地址:",@"*详细地址:",@"提交"];
    
    [self settableFrame];
}
-(void)settableFrame{
    Registertable=[[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-50) style:UITableViewStyleGrouped];
    Registertable.delegate=self;
    Registertable.dataSource=self;
    Registertable.showsVerticalScrollIndicator=NO;
    Registertable.backgroundColor=[UIColor groupTableViewBackgroundColor];
    [self.view addSubview:Registertable];
   
}
#pragma ----🌟🌟🌟UITableViewDataSource和UITableViewDelegate🌟🌟🌟

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    
    registerVCcell*cell=[[[NSBundle mainBundle]loadNibNamed:@"registerVCcell" owner:nil options:nil]firstObject];
    cell.TitleLable.attributedText=[self settextfiled:DataRgister[indexPath.section]];
    cell.TitleLable.font=[UIFont systemFontOfSize:16];
    cell.DetailFiled.textAlignment=0;
    cell.DetailFiled.tag=415+indexPath.section;
    cell.DetailFiled.delegate=self;
    if(indexPath.section==2){
        IDCardFiled=cell.DetailFiled;
    }
     [self setPalcehoderAndColor:indexPath.section WithCell:cell];
        
    return cell;


}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    return DataRgister.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
        return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 8;
    }else if (section==1||section==7){
        return 8;
    }
    if(section==6){
        
        return 290;
    }

    return 0.00000000000001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
       return 0.0001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.section==11) {
        return 55;
    }
    return 50;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section==6) {
        UIView*View=[[UIView alloc]initWithFrame:CGRectMake(0, 20, ScreenWidth, 290)];
        View.backgroundColor=[UIColor groupTableViewBackgroundColor];
        UIView*ContontV=[[UIView alloc]initWithFrame:CGRectMake(0, 8, ScreenWidth,290-16)];
        ContontV.backgroundColor=[UIColor whiteColor];
        [self addControllerForMypresent:ContontV];
        [View addSubview:ContontV];
        return View;
    }
    return 0;
}
#pragma mark----🌟🌟🌟业务逻辑的处理和设置Table的属性🌟🌟🌟
-(void)setPalcehoderAndColor:(long)section WithCell:(registerVCcell*)cell
{
    if (section==1||section==6) {
        cell.TitleLable.textColor=RGB(0, 128, 204);
        cell.DetailFiled.enabled=NO;
    }
    if(section==0){
        cell.IconV.hidden=NO;
        cell.DetailFiled.placeholder=@"     二维码扫描";
        cell.DetailFiled.enabled=NO;
    }else if (section==2){
        cell.DetailFiled.placeholder=@"     识别身份证信息";
        cell.DetailFiled.enabled=IsbringIDCar;
    }else if (section==3){
        cell.DetailFiled.enabled=NameIsEnd;
    }else if (section==4){
        cell.DetailFiled.keyboardType=UIKeyboardTypeNumberPad;
    }else if (section==5){
        cell.DetailFiled.placeholder=SendAddress;
    }else if (section==7){
        cell.DetailFiled.keyboardType=UIKeyboardTypeNumberPad;

    }else if (section==9){
        cell.DetailFiled.placeholder=@"输入地市自动索引";
        cell.DetailFiled.enabled=NO;
    }else if (section==11){
        [cell.contentView removeAllSubviews];
        
        UIButton*SubmiteBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        [cell.contentView addSubview:SubmiteBtn];
        [SubmiteBtn addTarget:self action:@selector(SubmitBtnOnckilck) forControlEvents:UIControlEventTouchUpInside];
        [SubmiteBtn setTitle:@"提交" forState:0];
        SubmiteBtn.layer.cornerRadius=5.0;
        [SubmiteBtn setBackgroundColor:AppNavColor];
        [SubmiteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(5);
            make.left.mas_equalTo(2);
            make.right.mas_equalTo(-2);
            make.bottom.mas_equalTo(-5);
        }];

    }
    if (section==0) {
        cell.DetailFiled.enabled=YES;
        cell.DetailFiled.text=Ordnumber;
        cell.DetailFiled.enabled=NO;
        
    }else if (section==2){
        cell.DetailFiled.text=IDCard;
    }else if (section==3){
        cell.DetailFiled.text=SendName;
    }else if (section==4){
        cell.DetailFiled.text=SendPhone;
    }else if (section==5){
        cell.DetailFiled.text=SendAddress;
    }else if (section==7){
        cell.DetailFiled.text=Acceptphone;
    }else if (section==8){
        cell.DetailFiled.text=AcceptName;
    }else if (section==9){
        cell.DetailFiled.text=AcceptAdress;
    }else if(section==10){
        cell.DetailFiled.text=acceptLocation;
    }
}
#pragma mark----🌟🌟🌟UITableViewDelegate点击Cell带哦哟个的代理方法🌟🌟🌟
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
  long section=indexPath.section;
    
  if (section==6||section==7||section==1) {
        NSLog(@"点击了图片详情页面或者是说明");
    }else{
        
        if(section==0){
//        打开扫描二维码的摄像头
        FistitemImage=nil;
        SecondItemImage=nil;
        FistOtherImage=nil;
        SecondItemImage=nil;
        BarCodeViewController*Barcode=[[BarCodeViewController alloc]init];
        [self.navigationController pushViewController:Barcode animated:YES];
        [Barcode returnText:^(NSString *showText) {
            Ordnumber=showText;
        [Registertable reloadData];
            
        }];
        }else if (section==2){
//        打开ORC技术读取身份证信息
            UIAlertView*Alert=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"你是随身带身份证？" delegate:self cancelButtonTitle:@"否" otherButtonTitles:@"是", nil];
            Alert.tag=252;
            [Alert show];
            
        }else if (section==5){
            

        }else if (section==9){
//        输入地市索引
            [self getLocationAdresss];
            
        }

    }

}
-(void)OpencameraInfomationwithtag:(long)tag  withBtn:(UIButton*)sender {
    
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        _pickerController = [[UIImagePickerController alloc] init];
        _pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        _pickerController.delegate = self;
        _pickerController.showsCameraControls = YES;
       
        if (tag==1) {
            
            _pickerController.view.tag=pickertag-1;
            
        }else if (tag==2){
            
            if (sender.tag==ImageBtnTag) {
                _pickerController.view.tag=pickertag+0;
            }else if (sender.tag==ImageBtnTag+1){
                 _pickerController.view.tag=pickertag+1;
            }else if (sender.tag==ImageBtnTag+2){
                _pickerController.view.tag=pickertag+2;
            }else if (sender.tag==ImageBtnTag+3){
                _pickerController.view.tag=pickertag+3;
            }
            
     }
   [self presentViewController:_pickerController animated:NO completion:nil];
   
    }
    else
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"由于您的设备暂不支持摄像头，您无法使用该功能!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确认", nil];
        alertView.tag=255;
        [alertView show];
       
    }
}
#pragma mark----🌟🌟🌟UIImagePickerControllerDelegate的方法实现🌟🌟🌟
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    if (picker.view.tag==pickertag-1) {
        UIImage *image;
        image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
        
        UIImageOrientation orientation = [image imageOrientation];
        
        CGImageRef imRef = [image CGImage];
        int texWidth = CGImageGetWidth(imRef);
        int texHeight = CGImageGetHeight(imRef);
        
        float imageScale = 1;
        
        if(orientation == UIImageOrientationUp && texWidth < texHeight)
            image = [UIImage imageWithCGImage:imRef scale:imageScale orientation: UIImageOrientationLeft];
        else if((orientation == UIImageOrientationUp && texWidth > texHeight) || orientation == UIImageOrientationRight)
            image = [UIImage imageWithCGImage:imRef scale:imageScale orientation: UIImageOrientationUp];
        else if(orientation == UIImageOrientationDown)
            image = [UIImage imageWithCGImage:imRef scale:imageScale orientation: UIImageOrientationDown];
        else if(orientation == UIImageOrientationLeft)
            image = [UIImage imageWithCGImage:imRef scale:imageScale orientation: UIImageOrientationUp];
        IDcardImageV.image=image;
        FistOtherImage=image;
        [self CommingtoIdentifyIDCard];
 
    }else if (picker.view.tag==pickertag){
     //获取图片信息
       FistitemImage=info[UIImagePickerControllerOriginalImage];
       [FistIteamBtn setImage:info[UIImagePickerControllerOriginalImage] forState:0];
        SecondIteamBtn.hidden=NO;
    }else if (picker.view.tag==pickertag+1){
        SecondItemImage=info[UIImagePickerControllerOriginalImage];

        [SecondIteamBtn setImage:info[UIImagePickerControllerOriginalImage] forState:0];
        SecondIteamBtn=info[UIImagePickerControllerOriginalImage];
    }else if (picker.view.tag==pickertag+2){
       [FistOtherBtn setImage:info[UIImagePickerControllerOriginalImage] forState:0];
        FistOtherImage=info[UIImagePickerControllerOriginalImage];
        SecondotherBtn.hidden=NO;
    }else if (picker.view.tag==pickertag+3){
     [SecondotherBtn setImage:info[UIImagePickerControllerOriginalImage] forState:0];
     SecondOtherImage=info[UIImagePickerControllerOriginalImage];
    }
    
      [picker dismissViewControllerAnimated:YES completion:nil];
    
}
//识别身份证方法
- (void)CommingtoIdentifyIDCard{
//    [self presentSheet];
    SendName=@"";
    IDCard=@"";
    [MBProgressHUD showMessag:@"正在识别...." toView:self.view];
    [self performSelector:@selector(startRec) withObject:nil afterDelay:0.01];

}
- (void)presentSheet {
    if (!progressSheet) {
        
        progressSheet = [[UIActionSheet alloc]
                         initWithTitle:@"识别中,请稍后⋯⋯"
                         delegate:self
                         cancelButtonTitle:@"取消"
                         destructiveButtonTitle:nil
                         otherButtonTitles: nil];
        
        progressSheet.actionSheetStyle =  UIActionSheetStyleAutomatic;
        
        NSLog(@"姿势图%@",progressSheet.subviews);
        //[[progressSheet.subviews lastObject] removeFromSuperview];
        
        progressBar = [[UIProgressView alloc] initWithFrame: CGRectZero];
        [progressBar setProgressViewStyle: UIProgressViewStyleBar];
        [progressSheet addSubview: progressBar];
     
        cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [cancelButton setBackgroundImage:[UIImage imageNamed:@"btn_bg.png"] forState: UIControlStateNormal];
        [cancelButton setTitle:@"取消" forState: UIControlStateNormal];
        [cancelButton addTarget:self action:@selector(cancelButtonPressed) forControlEvents:UIControlEventTouchDown];
        [progressSheet addSubview: cancelButton];
        
        
        activityView = [[UIActivityIndicatorView alloc]
                        initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhiteLarge];
        [progressSheet addSubview: activityView];
        [activityView startAnimating];
        
    }
    
    progressBar.frame = CGRectMake(30.0f, 45.0f, 320 - 60.0f, 9.0f);
    cancelButton.frame = CGRectMake(120.0, 60.0, 80.0, 30.0);
    activityView.frame = CGRectMake(320 / 2 - 20.0f, -120.0f, 40.0f, 40.0f);
    
    [progressBar setProgress:0.0f];
    //	[progressSheet showInView:self.view];
    [progressSheet showInView:[UIApplication sharedApplication].keyWindow];
}
- (void)cancelButtonPressed
{
    NSLog(@"Cancel button");
    self.isProgressCanceled = YES;
    
    progressBar.progress = 0.0;
    [self dismissPresentSheet];
}
- (BOOL)getCancelProcess
{
    return self.isProgressCanceled;
}

- (void)setCancelProcess:(BOOL)isCance
{
    self.isProgressCanceled = isCance;
}
- (void)dismissPresentSheet
{
    [progressSheet dismissWithClickedButtonIndex:0 animated:YES];
}

-(void)recongnitionResult:(id)sender
{
    _dataStr= sender;
    
    if ([_dataStr length])
    {
        if ([_dataStr isEqualToString:ERROR_SERVER]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:ERROR_SERVER
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
            
            [alert show];
     
            return;
        }
        if ([_dataStr isEqualToString:ERROR_TIMEOUT]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:ERROR_TIMEOUT
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
            
            [alert show];
     
            return;
        }
        if ([_dataStr isEqualToString:ERROR_NULL]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                            message:ERROR_NULL
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"确定", nil];
            
            [alert show];
     
            return;
        }
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:ERROR_NULL
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        
        [alert show];
      
        return;
    }
}
- (NSString *)makeCardResultWithStr:(NSString*)dataStr
{
    if (!dataStr.length){
        return nil;
    }
    
    return dataStr;
}


//点击“识别”按钮
- (void)startRec
{
    
    NSData *sendImageData = UIImageJPEGRepresentation(IDcardImageV.image, 0.75);
    
    NSUInteger sizeOrigin = [sendImageData length];
    NSUInteger sizeOriginKB = sizeOrigin / 1024;
    if (sizeOriginKB > 5*1024)
    {
        [self dismissPresentSheet];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"图片大小超过5M，请重试"
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"确定", nil];
        
        [alert show];
        return;
    }
    
    [self dismissPresentSheet];
    
    dispatch_source_t timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, 0ull*NSEC_PER_SEC), DISPATCH_TIME_FOREVER, 1ull*NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(timer, ^{
        PackageAPI *package = [[PackageAPI alloc] init];
        
        self.resultStr = [package uploadPackage:sendImageData andindexPath:0];
        NSData *data =[self.resultStr dataUsingEncoding:NSUTF8StringEncoding];
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        NSXMLParser  *par = [[NSXMLParser alloc]initWithData:data];
        
        par.delegate = self;
        
        [par parse];
        
        
    [self performSelectorOnMainThread:@selector(recongnitionResult:) withObject:self.resultStr waitUntilDone:YES];
        
        dispatch_source_cancel(timer);
    });
    
    dispatch_source_set_cancel_handler(timer, ^{
        NSLog(@"cancel");
//        dispatch_release(timer);
    });
//    启动
    dispatch_resume(timer);
}

#pragma mark----🌟🌟🌟获取地理位置🌟🌟🌟
#pragma mark - BMKLocal Service Delegate
/**
 *在停止定位后，会调用此函数
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    NSLog(@"%f  %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    BMKReverseGeoCodeOption  *option = [[BMKReverseGeoCodeOption alloc]init];
    option.reverseGeoPoint = userLocation.location.coordinate;
    BMKGeoCodeSearch *search = [[BMKGeoCodeSearch alloc]init];
    search.delegate = self;
    [search reverseGeoCode:option];
    //    NSAssert(work, @"根据地理坐标获取地址信息失败");
    [locService stopUserLocationService];
    
}

- (void)didFailToLocateUserWithError:(NSError *)error
{
    SendAddress = @"定位失败，请手动输入";
}

#pragma mark - BMKGeoCodeSearch Delegate

- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
        SendAddress = result.address;
        addressStr = result.address;
        reportAddress = [NSString stringWithFormat:@"%@%@",result.addressDetail.province,result.addressDetail.city];
        [Registertable reloadData];
}
-(void) viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark----🌟🌟🌟实现本页面的HTTP请求的参数格式🌟🌟🌟
-(void) SubmitBtnOnckilck{
    
    [NotUpImageArray removeAllObjects];
    [NotUpDataArray removeAllObjects];
    NSDictionary*Registdata=[NSDictionary dictionary];
    //寄件的基本信息
    _Photos1Array=[NSMutableArray array];
    _Photos2Array=[NSMutableArray array];
    
    if ([self checktextfiledisnill]==NO) {
        return;
    }
    
    Registdata=@{@"orderNo":Ordnumber,@"senderIdNo":IDCard,@"senderName":SendName,@"senderPhone":SendPhone,@"senderAddressAuto":SendAddress,@"receiverName":AcceptName,@"receiverPhone":Acceptphone,@"receiverProvince":Acceptprovince,@"receiverCity":AcceptCity,@"receiverArea":Accepttown,@"receiverAddress":acceptLocation,@"employeeid":[UserData shareUserData].userModel.dbId,@"employeeName":[UserData shareUserData].userModel.name};
   
    NSLog(@"%d",[[UserData shareUserData].userModel.uploadDataMode intValue]);
    
    NSString*UserStatic =[UserDefaults objectForKey:uploadDataModeStatic];
    
    if ([UserStatic intValue]==1) {
        
        [self UploadFormTosevers:Registdata WithIndex:0];
    }else{
        
        [self UploadFormTosevers:Registdata WithIndex:1];
    }
    
   
    [MBProgressHUD showMessag:@"正在提交..." toView:self.view];
    
   }
#pragma mark----🌟🌟🌟UitextfiledDelegate的方法🌟🌟🌟


-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField.tag==415) {
        Ordnumber =textField.text;
    }else if(textField.tag==417){
        IDCard=textField.text;
        IsbringIDCar=NO;
    }
    else if (textField.tag==418){
        SendName=textField.text;

    }else if (textField.tag==420){
        SendAddress=textField.text;
    }
    else if (textField.tag==419){
        SendPhone=textField.text;
    }else if (textField.tag==422){
        Acceptphone=textField.text;
    }else if (textField.tag==423){
        AcceptName=textField.text;
    }else if (textField.tag==424){
        AcceptAdress=textField.text;
    }else if (textField.tag==425){
        acceptLocation=textField.text;
    }
    [Registertable reloadData];
  }
#pragma mark----🌟🌟🌟节点解析 .获取身份证的信息🌟🌟🌟
//准备节点
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(NSDictionary<NSString *, NSString *> *)attributeDict{
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    self.currentElement = elementName;
    
}
//获取节点内容
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    
    if ([self.currentElement isEqualToString:@"name"])
    {
        [_dict setValue:string forKey:@"name"];
     
        SendName=string;
    }
    else if
        ([self.currentElement isEqualToString:@"cardno"])
    {
        [_dict setObject:string forKey:@"cardno"];
        NSString*IDString=[string substringWithRange:NSMakeRange(0,18)];
        IDCard=IDString;
        
    }
    
    NameIsEnd=NO;
    [Registertable reloadData];
}

//解析完一个节点
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName{
    
    if ([elementName isEqualToString:@"student"]) {
        //        [self.list addObject:self.person];
    }
    self.currentElement = nil;
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    
    [picker dismissViewControllerAnimated:NO completion:nil];
}

//获取图片的信息
-(void)getBlackImageforbtn:(UIButton*)sender{
    
    [self OpencameraInfomationwithtag:2 withBtn:sender];

}

//设置图片管理的内容
-(void)addControllerForMypresent:(UIView*)cell{
    UILabel*Lable=[[UILabel alloc]init];
    [Lable setText:@"  图片信息"];
    
    Lable.layer.borderWidth=1.3;
    Lable.layer.borderColor=[UIColor groupTableViewBackgroundColor].CGColor;
    Lable.textColor=AppNavColor;
    Lable.font=[UIFont systemFontOfSize:15];
    [cell addSubview:Lable];
    [Lable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(50);
    }];
    
    UILabel*IteamL=[[UILabel alloc]init];
    

    IteamL.attributedText=[self settextfiled:@"*物品图片"];
    IteamL.font=[UIFont systemFontOfSize:15];
    [cell addSubview:IteamL];
    [IteamL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(45);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];
    FistIteamBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    FistIteamBtn.tag=ImageBtnTag+0;
    [cell addSubview:FistIteamBtn];
//    SecondIteamBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//    SecondIteamBtn.tag=ImageBtnTag+1;
//    [cell addSubview:SecondIteamBtn];
    [FistIteamBtn addTarget:self action:@selector(getBlackImageforbtn:) forControlEvents:UIControlEventTouchUpInside];
    if(FistitemImage){
        [FistIteamBtn setImage:FistitemImage forState:0];
        SecondIteamBtn.hidden=NO;
    }else{
        [FistIteamBtn setImage:[UIImage imageNamed:@"Add_Image"] forState:0];
        SecondIteamBtn.hidden=YES;
    }

    [FistIteamBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(85);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];
    
//    [SecondIteamBtn addTarget:self action:@selector(getBlackImageforbtn:) forControlEvents:UIControlEventTouchUpInside];
//    if(SecondItemImage){
//       [SecondIteamBtn setImage:SecondItemImage forState:0];
//    }else{
//       [SecondIteamBtn setImage:[UIImage imageNamed:@"Add_Image"] forState:0];
//        SecondIteamBtn.hidden=YES;
//    }
//
//    [SecondIteamBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(85);
//        make.left.mas_equalTo(120);
//        make.width.mas_equalTo(70);
//        make.height.mas_equalTo(70);
//    }];
   
    UILabel*Other=[[UILabel alloc]init];
    Other.attributedText=[self settextfiled:@" 其他证件图片"];
    Other.font=[UIFont systemFontOfSize:15];

    [cell addSubview:Other];
    [Other mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(153);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];

    FistOtherBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [cell addSubview:FistOtherBtn];
//    SecondotherBtn=[UIButton buttonWithType:UIButtonTypeCustom];
//    [cell addSubview:SecondotherBtn];
    [FistOtherBtn addTarget:self action:@selector(getBlackImageforbtn:) forControlEvents:UIControlEventTouchUpInside];
    FistOtherBtn.tag=ImageBtnTag+2;
    if(FistOtherImage){
        [FistOtherBtn setImage:FistOtherImage forState:0];
        SecondotherBtn.hidden=NO;
    }else{
        [FistOtherBtn setImage:[UIImage imageNamed:@"Add_Image"] forState:0];
//        SecondotherBtn.hidden=YES;
    }
    [FistOtherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(190);
        make.left.mas_equalTo(10);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];
  
//    SecondotherBtn.tag=ImageBtnTag+3;
//    [SecondotherBtn addTarget:self action:@selector(getBlackImageforbtn:) forControlEvents:UIControlEventTouchUpInside];
//    if(SecondOtherImage){
//       [SecondotherBtn setImage:SecondOtherImage forState:0];
//    }else{
//        
//      [SecondotherBtn setImage:[UIImage imageNamed:@"Add_Image"] forState:0];
//    }
   
    [SecondotherBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(190);
        make.left.mas_equalTo(120);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];

}
#pragma mark----🌟🌟🌟获取接收地址的方法🌟🌟🌟
-(void)getLocationAdresss{
     [self getPickerData];
    backView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
    backView.backgroundColor=[[UIColor blackColor]colorWithAlphaComponent:0.2];
    [SharedApplication.keyWindow addSubview:backView];
    PickView=[[UIPickerView alloc]init];
    [backView addSubview:PickView];
    PickView.backgroundColor=[UIColor redColor];
    [PickView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(200);
    }];
    contextbtnV=[[UIView alloc]init];
    [backView addSubview:contextbtnV];
    contextbtnV.backgroundColor=[UIColor whiteColor];
    [contextbtnV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-200);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(40);
    }];

    UIButton*canBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [canBtn setTitle:@"取消" forState:0];
    [canBtn addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchUpInside];
    canBtn.tag=btnPicKTag;
    [contextbtnV addSubview:canBtn];
    [canBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    [canBtn setTitleColor:AppNavColor forState:0];
    
    UIButton*sureBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [sureBtn setTitle:@"确定" forState:0];
    [sureBtn addTarget:self action:@selector(cancelBtn:) forControlEvents:UIControlEventTouchUpInside];
    [contextbtnV addSubview:sureBtn];
    sureBtn.tag=btnPicKTag+1;
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    [sureBtn setTitleColor:AppNavColor forState:0];
    
    PickView.backgroundColor=[UIColor whiteColor];
    PickView.delegate=self;
    PickView.dataSource=self;
   
}
- (void)getPickerData {
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Address" ofType:@"plist"];
    self.pickerDic = [[NSDictionary alloc] initWithContentsOfFile:path];
    
    self.provinceArray = [self.pickerDic allKeys];
    
    self.selectedArray = [self.pickerDic objectForKey:[[self.pickerDic allKeys] objectAtIndex:0]];
    
    if (self.selectedArray.count > 0) {
        self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
    }
    
    if (self.cityArray.count > 0) {
        self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
    }
    
}

-(void)ClearAlldata{
    Ordnumber=nil;//单号信息
    IDCard=nil;//身份证号
    SendName=nil;//寄件人姓名
    SendPhone=nil;//寄件人手机号码
    SendAddress=@"";//寄件人地址
    Acceptphone=nil;//收件人手机号码
    AcceptName=nil;//收件人姓名
    AcceptAdress=nil;//收件人地址
    FistitemImage=nil;
    SecondItemImage=nil;
    FistOtherImage=nil;
    SecondOtherImage=nil;
    acceptLocation=nil;
    Accepttown=nil;
    AcceptCity=nil;
    IsbringIDCar=NO;
    Acceptprovince=nil;
    [locService startUserLocationService];

    [Registertable reloadData];
}
-(BOOL)checktextfiledisnill{
    if(Ordnumber==nil){

        [MBProgressHUD showError:@"单号信息为空" toView:self.view];
        return NO;
    }else if (IDCard==nil){

        [MBProgressHUD showError:@"身份证号为空" toView:self.view];

        return NO;
    }else if (SendName==nil){
        
        [MBProgressHUD showError:@"寄存姓名为空" toView:self.view];
        
        return NO;
    }else if ([self checkTel:SendPhone]==NO){
        return NO;
    }else if (SendAddress==nil){
        
        [MBProgressHUD showError:@"寄件地址为空" toView:self.view];
        
        return NO;
    }
    if (FistitemImage) {
        
        [_Photos1Array addObject:FistitemImage];
        
    }else{
        
      [MBProgressHUD showError:@"请上传物品图片" toView:self.view];

        return NO;
    }

    if (FistOtherImage) {
        
        [_Photos2Array addObject:FistitemImage];
        
    }

    if([self checkTel:Acceptphone]==NO){
        return NO;
    }
    
    if (AcceptName.length==0){

        [MBProgressHUD showError:@"收件姓名为空" toView:self.view];

        return NO;
    }
    if (AcceptAdress.length==0) {
        [MBProgressHUD showError:@"收件地址为空" toView:self.view];
        return NO;
    }
    if (acceptLocation.length==0) {
        [MBProgressHUD showError:@"详细地址不为空" toView:self.view];
        return NO;
    }
    return YES;
}
#pragma mark - UIPicker Delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (component == 0) {
        return self.provinceArray.count;
    } else if (component == 1) {
        return self.cityArray.count;
    } else {
        return self.townArray.count;
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        return [self.provinceArray objectAtIndex:row];
    } else if (component == 1) {
        return [self.cityArray objectAtIndex:row];
    } else {
        return [self.townArray objectAtIndex:row];
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    if (component == 0) {
        return 100;
    } else if (component == 1) {
        return 150;
    } else {
        return 100;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    if (component == 0) {
        self.selectedArray = [self.pickerDic objectForKey:[self.provinceArray objectAtIndex:row]];
        
        if (self.selectedArray.count > 0) {
            self.cityArray = [[self.selectedArray objectAtIndex:0] allKeys];
        } else {
            self.cityArray = nil;
        }
        
        if (self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:0]];
        } else {
            self.townArray = nil;
        }
    }
    [pickerView selectedRowInComponent:1];
    [pickerView reloadComponent:1];
    [pickerView selectedRowInComponent:2];
    
    if (component == 1) {
        if (self.selectedArray.count > 0 && self.cityArray.count > 0) {
            self.townArray = [[self.selectedArray objectAtIndex:0] objectForKey:[self.cityArray objectAtIndex:row]];
        } else {
            self.townArray = nil;
        }
        [pickerView selectRow:1 inComponent:2 animated:YES];
        
    }
    
    [pickerView reloadComponent:2];
}
-(void)cancelBtn:(UIButton*)sender{
    if (sender.tag==btnPicKTag+1) {
        
        Acceptprovince=[self.provinceArray objectAtIndex:[PickView selectedRowInComponent:0]];
        
        AcceptCity=[self.cityArray objectAtIndex:[PickView selectedRowInComponent:1]];
        Accepttown=[self.townArray objectAtIndex:[PickView selectedRowInComponent:2]];
        AcceptAdress=[NSString stringWithFormat:@"%@-%@-%@",Acceptprovince,AcceptCity,Accepttown];
        [Registertable reloadData];
    }
    [UIView animateWithDuration:0.3 animations:^{
        PickView.frame=CGRectMake(0, ScreenHeight, ScreenWidth, 200);
        contextbtnV.frame=CGRectMake(0, ScreenHeight, ScreenWidth, 40);
    } completion:^(BOOL finished) {
        [backView removeFromSuperview];
    }];

   
}
-(BOOL) isConnectionAvailable{
    
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    
    if ([reach currentReachabilityStatus]==ReachableViaWiFi) {
        return YES;
    }else{
        return NO;
    }
  
}
-(NSMutableAttributedString*)settextfiled:(NSString*)Str{

    NSMutableAttributedString *attributedStr= [[NSMutableAttributedString alloc] initWithString:Str];
    [attributedStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 1)];
    [attributedStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, 1)];
    return attributedStr;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==252) {
        if (buttonIndex==0) {
            IsbringIDCar=YES;
            NameIsEnd=YES;
            [Registertable reloadData];
            [IDCardFiled becomeFirstResponder];
            
        }else{
             [self OpencameraInfomationwithtag:1 withBtn:nil];
            
        }
     
    }
    
    if (alertView.tag==255) {
        if (buttonIndex==0) {
           
        }else{
            if (buttonIndex==1)
            {
                [[UserData shareUserData] loginOut];
                
                [self toLoginVC];
                
                [self.tabBarController setSelectedIndex:0];
                
                [SharedNotifiCenter postNotificationName:isLoginSuccess object:nil];
            }

        }

    }
    
   
}

/* Registdata  这个是一个需要写入内存的参数信息
 **说明:写入内存不一定使用。但是可以根据图片删除
 */
-(void)writetomemory:(NSDictionary*)Registdata{
    
    BOOL WriteBool;
    
    NSMutableDictionary*Regdiction=[NSMutableDictionary dictionaryWithDictionary:Registdata];
    //将数据写入沙盒中，等待上传
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"MM-dd"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    [Regdiction setValue:dateStr forKey:@"TimeStep"];
    
    //做存储操作
    NSDictionary*diction=[UserDefaults objectForKey:imagecount];
    
    if ([diction[@"imagecount"] integerValue]) {
        
        ImageCount=[diction[@"imagecount"]  integerValue];
        
    }
    if (FistitemImage) {
        
        if(FistOtherImage){
            
            [NotUpdataTool SaveImageDatatoSanbox:0 WithImage:FistitemImage WithImagePath:ImageCount];
            WriteBool=[NotUpdataTool SaveImageDatatoSanbox:1 WithImage:FistOtherImage WithImagePath:ImageCount];
            
        }else{
           WriteBool=[NotUpdataTool SaveImageDatatoSanbox:0 WithImage:FistitemImage WithImagePath:ImageCount];
        }
        
        if (WriteBool==YES) {
            [NotUpdataTool SaveImageDatatoSanboxWithDict:Regdiction WithImageDictIndex:ImageCount];
        }
    }
    
    ImageCount=ImageCount+1;
    
    if (WriteBool==YES) {
        
        NSMutableDictionary*Diccont=[NSMutableDictionary dictionary];
        [Diccont setObject:[NSString stringWithFormat:@"%ld",ImageCount] forKey:@"imagecount"];
        [UserDefaults setObject:Diccont forKey:imagecount];
        
    }

    
    [self ClearAlldata];
    
    [MBProgressHUD showSuccess:@"写入内存成功" toView:self.view];
}

/*image       这个是上传的图片信息
 **type       这个是这个是上传的图片类型 0表示物品图片 1表示其他证件图片
 **RecondID   这个是表单提交是返回的参数
 ***说明:      这个方法是上传图片的方法。单个图片上传
 */

-(void)UploadImageForSevers:(UIImage*)image withtype:(NSString*)type RecondID:(NSString*)RecondID{
    @synchronized (self) {
        
        AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
        
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
        NSMutableDictionary*Registdata=[NSMutableDictionary dictionary];
        NSData*ImageData=UIImageJPEGRepresentation(image, 0.4);
        NSString*Base64image=[ImageData base64EncodedStringWithOptions:0];
        [Registdata setObject:Base64image forKey:@"base64"];
        [Registdata setObject:@"png" forKey:@"extname"];
        [Registdata setObject:RecondID forKey:@"orderdbid"];
        [Registdata setObject:type forKey:@"type"];
        [manager POST:@"http://wjw.szgaj.cn/jdcj_fastdfs_client/api/fastdfs/upload" parameters:Registdata success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            
        }];
    }
}

/*Registdata 传进来的参数
 **index   这个是表示当前的网路是否可以上传图片
 **index  0表示可以直接上传 1表示非WIFI上传存起来。WIFI下可以上传
 ***说明:  当状态是1的时候会还要判断网络是不是当
 */
-(void)UploadFormTosevers:(NSDictionary*)Registdata WithIndex:(long)index{
    
    AFHTTPRequestOperationManager *manager  = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"text/json", @"application/json", nil];
    [manager POST:[BaseUrl stringByAppendingString:[APIAdress managementAds]] parameters:Registdata constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        
    }success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([responseObject[@"code"] integerValue]==200) {
            NSDictionary*dataDic =responseObject[@"data"];
            [MBProgressHUD showSuccess:responseObject[@"desc"] toView:self.view];
    
            if (index==0) {
                if(FistitemImage){
                    [self UploadImageForSevers:FistitemImage withtype:@"1" RecondID:dataDic[@"recordid"]];
                    }
                if (FistOtherImage) {
                    [self UploadImageForSevers:FistOtherImage withtype:@"2" RecondID:dataDic[@"recordid"]];
                    }
           }else{
        if ([self isConnectionAvailable]==NO){
                    //将数据写入沙盒中，等待上传
                    NSMutableDictionary*RegiMutabDic=[NSMutableDictionary dictionaryWithDictionary:Registdata];
                    [RegiMutabDic setObject:dataDic[@"recordid"] forKey:@"recordid"];
                    
                    [self writetomemory:RegiMutabDic];
                    
                }else{
                    if(FistitemImage) {
                        [self UploadImageForSevers:FistitemImage withtype:@"1" RecondID:dataDic[@"recordid"]];
                    }
                    if (FistOtherImage) {
                        [self UploadImageForSevers:FistOtherImage withtype:@"2" RecondID:dataDic[@"recordid"]];
                }

               }
          }
    [self ClearAlldata];
        
    }
            
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        [MBProgressHUD showError:@"提交失败.." toView:self.view];
        
    }];

}

@end
